package com.ecs.server.datadealer;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.hibernate.classic.Session;

import com.ecs.message.ECSMessage;
import com.ecs.message.Illuminance;
import com.ecs.message.Temperature;

public class ServerSender implements Runnable {
	
	Socket s;
	
	public ServerSender(Socket s)
	{
		// TODO Auto-generated constructor stub
		this.s = s;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Timer timer = new Timer();
		timer.schedule(new Monitor(),10000,5000);
		
	}
	
	class Monitor extends TimerTask
	{
		ECSMessage message = null;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			//System.out.println("A Check is excuting!");
			message = illuminanceCheck();
			if(message != null)
			{
				ObjectOutputStream oos;
				try {
					oos = new ObjectOutputStream(s.getOutputStream());
					oos.writeObject(message);
					System.out.println("A warning message has been send out!");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}
	
	private ECSMessage illuminanceCheck()
	{
		//System.out.println("A check is start!");
		Session session = ClientManager.factory.openSession();
		session.beginTransaction();
		List search  = session.createQuery("select new Illuminance(id,networkId,nodeId,sensorId,value,date) from Illuminance " +
				"where id=(select max(id) from Illuminance)").list();
		for(int i = 0; i < search.size(); i++ )
		{
			Illuminance illuminance = (Illuminance)search.get(i);
			
			if(Integer.parseInt(illuminance.getValue()) == 0)
			{
				System.out.println("The light is turn off!");
				ECSMessage message = new ECSMessage();
				message.setMessageType("Warning");
				message.setMeasureType("Illuminance");
				message.setContent(search);
				return message;
			}
		}
		
		return null;
	}

}
